package com.javenwong.android.engine;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.Log;

public class ImageManager {
	
	/** 标准屏幕宽，做为画布缩放的基础 */
	public static int STANDARD_WIDTH = 800;
	/** 标准屏幕高，做为画布缩放的基础 */
	public static int STANDARD_HEIGHT = 480;
	
	/** 宽的缩放比例 */
	public static float SCALE_WIDTH;
	/** 高的缩放比例 */
	public static float SCALE_HEIGHT;

	public static final int SCALE_TYPE_FILL = 0;	//满屏（拉伸 ）
	public static final int SCALE_TYPE_RATIO = 1;	//比例缩放（有黑边）
	public static int SCALE_TYPE = SCALE_TYPE_FILL;
	
	public static final Matrix MATRIX = new Matrix();
	public static float translateX,translateY;
	
	/**
	 * 从asset中获取 Bitmap
	 * @param assetPath
	 * @return
	 */
	public static final Bitmap getBitmap(String assetPath){

		Bitmap bitmap = null;
		if (assetPath.startsWith("/")) {
			assetPath = assetPath.substring(1);
		}
		//创建Bitmap
		try {
			bitmap = BitmapFactory.decodeStream(GameActivity.assetManager.open(assetPath));
		} catch (IOException e) {
			Log.d("Bitmap error", assetPath);
			e.printStackTrace();
		}

		return bitmap;
	}
	
	/**
	 * 计算画布缩放比率
	 * @param SW 画布宽
	 * @param SH 画布高
	 */
	public static final void jsScale(int SW, int SH){

		if (SCALE_TYPE==SCALE_TYPE_FILL){
			ImageManager.SCALE_WIDTH = (float) SW / ImageManager.STANDARD_WIDTH;
			ImageManager.SCALE_HEIGHT = (float) SH / ImageManager.STANDARD_HEIGHT;
			
			ImageManager.MATRIX.setScale(ImageManager.SCALE_WIDTH, ImageManager.SCALE_HEIGHT);
		}else if (SCALE_TYPE==SCALE_TYPE_RATIO){
			ImageManager.SCALE_WIDTH = (float) SW / ImageManager.STANDARD_WIDTH;
			ImageManager.SCALE_HEIGHT = (float) SH / ImageManager.STANDARD_HEIGHT;
			
			translateX = 0;
			translateY = 0;
			
			float scale = ImageManager.SCALE_WIDTH;
			
			if (SCALE_WIDTH<SCALE_HEIGHT){
				scale = SCALE_WIDTH;
				translateY = (SH-STANDARD_HEIGHT*scale)/2;
			}else if (SCALE_WIDTH>SCALE_HEIGHT){
				scale = SCALE_HEIGHT;
				translateX = (SW-STANDARD_WIDTH*scale)/2;
			}
			
			ImageManager.SCALE_WIDTH = ImageManager.SCALE_HEIGHT = scale;

			ImageManager.MATRIX.setScale(ImageManager.SCALE_WIDTH, ImageManager.SCALE_HEIGHT);
			MATRIX.postTranslate(translateX, translateY);			

		}
		
	}
	
	/**
	 * 自动缩放 Bitmap
	 * @param bitmap
	 * @return
	 */
	@Deprecated
	public static final Bitmap getBitmap(Bitmap bitmap){

		if (SCALE_HEIGHT==1 && SCALE_WIDTH==1){
			return bitmap;
		}
		
		//缩放
		MATRIX.setScale(SCALE_WIDTH, SCALE_HEIGHT);
		
		return Bitmap.createBitmap(bitmap, 0, 0, 
				bitmap.getWidth(), bitmap.getHeight(), 
				MATRIX, true);
	}
}
